<?php
  
 /**
 * 
 */

defined('ACC') || exit('ACC deined');

 class goodModel extends Model {
  
    protected  $table = 'goods';
    protected $pk = 'goods_id';
    public $fields = array('goods_id','goods_sn','cat_id','brand_id','goods_name',
      'shop_price','market_price','goods_number','click_count','goods_weight',
      'goods_brief','goods_desc','thumb_img','goods_img','ori_img','is_on_sale',
      'is_delete','is_best','is_new','is_hot','add_time','lost_update','keywords');

  //自动填充(暂时没用上)
   protected $_auto = array(
                   array('is_hot','value',0),
                   array('is_new','value',0),
                   array('is_best','value',0),
                   array('add_time','function','time')
   );

    /**
      验证规则, 参数1: 验证的字段名
               参数2: 验证规则 0:可以不填，但是填了必须满足规则 1:必填 2:如果有，且内容不为空，则检查， 
               参数3：错误信息
               参数4: 具体规则
               参数5: 具体规则对应的数据
    */
    public $rule = array(
      ['goods_name',1,'商品名不能为空','required',''],
      ['cat_id',1,'商品分类必须为数字','numeric',''],
      ['goods_brief',2,'商品描述必须在5-100个字符之间','between','5,100'],
      ['is_new',0,'是否新品只能是0或1','in','0,1'],
      ['goods_sn',1,'商品货号不能重复','unique',''],
    );
  
  /*
     负责把传来的数组
     清除掉不用的单元
     留下与表的字段对应的单元
     思路：
       循环数组，分别判断其键(key),是否是表的字段
        当然，要先定义或者获取表的字段（我这边直接手动定义）
    */
    //处理表单接收到的数据
    function shiftData($data){
      $dd = array();
     foreach ($data as $key => $value) {
         if(in_array($key,$this->fields)){
                if ($key == 'goods_weight') {
                      if($value){
                          $dd[$key] =$value * $data['weight_unit']; 
                      }
                      
                  }else{
                      $dd[$key] = $value;
                }
         }
    }
         return $dd;
  }
    // function getall(){
    //    $sql = 'select * from ' . $this->table;
    //    return $this->db->getAll($sql);
    // }


  /**
    作用：把商品放到回收站，即is_delete = 1
    parm int id
    return bool
  **/
   function trash($id){
     return $this->update(array('is_delete'=>'1') , $id);
   }

  /**
   获取goods表里的所有数据，除了加入回收站的
  **/
  function getGoods($limit=0,$start=0){
      $sql = 'select * from ' . $this->table . ' where is_delete = 0 order by goods_id desc';
      if(!empty($limit)){
          $sql .= " limit $start,$limit";
      }
       return $this->db->getAll($sql);
   }

   //获取回收站所有商品
   function getTrash($limit=0,$start=0){
     $sql = 'select * from ' . $this->table . ' where is_delete = 1 order by goods_id desc';
       if(!empty($limit)){
           $sql .= " limit $start,$limit";
       }
     return $this->db->getAll($sql);
    }


   //自动生成商品货号
   function autoNum(){
      $num = 'bl' . date('Ymd') . mt_rand('11111','99999');

      $sql = 'select count(*) as count from goods where goods_sn = "' . $num . '"';

       if($this->db->getRow($sql)['count'] > 0){
          $this->autoNum();
        }
            return $num;
   }

  //获取新品商品 默认5个
  public function getNewGoods($len=5){
     $sql = 'select goods_id,goods_sn,cat_id,brand_id,goods_name,shop_price,market_price,goods_number,
         concat("'.SER_ROOT.'",thumb_img) as thumb_img,is_delete,is_new,is_hot 
      from ' . $this->table .' 
     where is_new = 1 and is_delete = 0 and is_on_sale = 1 order by goods_id desc limit ' . $len;
       return $this->db->getAll($sql);
   }

   //获取传入的父栏目 下的所有子栏目的详细商品信息
     /**
      *     取出栏目下的商品
      * @param $parent 父栏目ID
      * @param $limit 每页取出的数据长度
      * @param $start 用于分页，表示开始从那里开始取数据
      */
    public function getColumnDetail($parent,$limit=5,$start=0){
        //找到栏目的 子孙栏目
     $catmode = new catModel;
     $childId = $catmode->lookChildTree($parent);
     array_unshift($childId,$parent);
     $childId = implode(',',$childId);

        //取出子孙栏目对应的 商品数据    /增加按销量排序
      $goodsql = 'select goods_id,goods_sn,cat_id,brand_id,goods_name,shop_price,market_price,
             goods_number, concat("'.SER_ROOT.'",thumb_img) as thumb_img
             ,concat("'.SER_ROOT.'",goods_img) as goods_img
             ,concat("'.SER_ROOT.'",ori_img) as ori_img
             ,is_delete,is_new,is_hot 
      from '. $this->table . ' 
      where cat_id in (' . $childId . ') and is_delete = 0 and is_on_sale = 1 order by sell_number desc limit '. $start .  ',' .$limit;

        return $this->db->getAll($goodsql);
    }


     /**
      *     取出栏目下的商品个数
      * @param $parent 父栏目ID
      */
     public function getColumnCount($parent){
         //找到栏目的 子孙栏目
         $catmode = new catModel;
         $childId = $catmode->lookChildTree($parent);
         array_unshift($childId,$parent);
         $childId = implode(',',$childId);


         //取出子孙栏目对应的 商品数据
         $goodsql = 'select count(*) from '. $this->table . ' where cat_id in (' . $childId .') and is_delete = 0 and is_on_sale = 1';

         return $this->db->getone($goodsql);
     }


     /**
       * 获取一个指定的商品
       * @paran $id  商品ID
      */
     public function getOneGoods($id){
        $sql = 'select goods_id,goods_sn,cat_id,brand_id,goods_name,shop_price,goods_weight,goods_brief
           , concat("'.SER_ROOT.'",goods_img) as goods_img,market_price,goods_number
           , concat("'.SER_ROOT.'",thumb_img) as thumb_img
           , goods_img as good_img,is_on_sale
           ,is_delete,is_new,is_hot,goods_desc
           ,keywords
           ,sell_number from ' . $this->table .' where goods_id = ' . $id;
        return $this->db->getRow($sql);
      }


      /**
       * 获取 加购的商品的详细信息
       * @param $all 购物车的所有商品信息
       */
      public function getCatDetail($all){
          foreach($all as $k=>$v){
              //单独取购物车里的每一条商品，去掉已经下架的和删除的
              $sql = 'select goods_id,goods_sn,cat_id,goods_name,shop_price
              ,concat("'.SER_ROOT.'",goods_img) as goods_img
              ,market_price,goods_number,concat("'.SER_ROOT.'",thumb_img) as thumb_img,is_delete
              ,is_on_sale,goods_desc,sell_number from ' . $this->table .
                  ' where goods_id = ' . $k .' and is_delete = 0 and is_on_sale = 1';
              $d = $this->db->getRow($sql);
              if(!empty($d)){
                  $all[$k]['goods_id'] = $d['goods_id'];
                  $all[$k]['shop_price'] = $d['shop_price'];
                  $all[$k]['goods_number'] = $d['goods_number'];
                  $all[$k]['thumb_img'] = $d['thumb_img'];
                  $all[$k]['market_price'] = $d['market_price'];

              }
          }
          return $all;
      }

      /**
       * 获取销售排行前十的商品
       */
      public function getSellMore(){
          $sql = 'select goods_id,goods_sn,cat_id,goods_name,shop_price,concat("'.SER_ROOT.'",goods_img) as goods_img
                 ,market_price,goods_number
                 ,concat("'.SER_ROOT.'",thumb_img) as thumb_img,is_delete,is_on_sale,goods_desc,sell_number from '
              . $this->table . ' where is_delete = 0 and is_on_sale = 1 order by sell_number desc limit 10';
          return $this->db->getAll($sql);
      }


      /**
       *  取出浏览历史里的商品
       *  $count  取出商品个数
       */
      public function getHistory($count='all'){
          if(!isset($_COOKIE['history'])){
              return [];
          }
          $his = array_slice(explode(',',$_COOKIE['history']),0,$count,true);
          $data = [];

          //修改，按cookie中存入的顺序取出来排列
          foreach($his as $v){
              $sql = 'select goods_id,goods_name,shop_price,market_price,cat_id
                 ,goods_number,concat("'.SER_ROOT.'",thumb_img) as thumb_img from '
                  . $this->table . ' where is_delete = 0 and is_on_sale =1 and goods_id = ' . $v;

              array_push($data,$this->db->getRow($sql));
          }

          return $data;
      }


      /**
       * 更新商品信息
       */
      public function goodUpdate($data){
//          $sql = 'update ' . $this->table . 'set where goodsId = ' . $goodsId . ' ';
          $where = ' where goods_id = ' . $data['goods_id'];
          return $this->db->autoExecute($this->table,$data,'update',$where);
      }





 }

